package com.dingli.shop.controller;

import com.dingli.shop.biz.LoginBiz;
import com.dingli.shop.entity.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    private LoginBiz login;

    //间接访问
    @RequestMapping(value = "/reg1")
    public String reg1(){
        return "reg";
    }

    @RequestMapping(value = "/login1")
    public String login1(){
        return "login";
    }



    //注册
    @PostMapping(value = "/reg")//前端传递过来的数据 可以构成user对象
    //@RequestMapping(value = "/reg",method = RequestMethod.POST)
    public String reg(TUser user, Model model){
        //判断邮箱是否被注册
        int i = login.checkEmail(user.getEmail());
        if(i == 0){//没有重复，可以注册
            if(login.insertUser(user) == 1) {//插入到数据库
                return "login";
            }
        }else if(i == -1){
            model.addAttribute("message","输入的信息有误！");
        }else  if(i == -2){
            model.addAttribute("message","数据库异常");
        }else {
            model.addAttribute("message","邮箱已被注册，请更换其他的邮箱注册！");
        }
        return "reg";
    }

    //登录
    @PostMapping(value = "/login")//前端传递过来的数据 可以构成user对象
    public String login(TUser user, Model model, HttpServletRequest request){
        int i = login.login(user);
        if(i == 1){
            //将登录用户对象保存在会话数据域中 名字叫user  会话域中的数据可以长期保存，在用户关闭浏览器的时候结束，或者是5分钟操作以内
            //Model model 只能保存本次跳转，之后就不能使用
            request.getSession().setAttribute("users",user);
            return "index";
        }else  if(i == 0){
            model.addAttribute("message","用户名或者密码错误！");
        }else if(i == -1){
            model.addAttribute("message","输入的信息有误！");
        }
        return "login";
    }





}
